package com.alogic.xscript.plugins;

import com.alogic.matcher.CommonMatcher;
import com.alogic.matcher.MatcherFactory;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;

/**
 * 通用匹配器
 */
public class Matcher extends Segment {
    protected String id = "";
    protected String $pattern = "";
    protected String $value = "";

    public Matcher(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);

        id = PropertiesConstants.getString(p,"id","$" + this.getXmlTag(),true);
        $pattern = PropertiesConstants.getRaw(p,"pattern",$pattern);
        $value = PropertiesConstants.getRaw(p,"value",$value);
    }

    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx, ExecuteWatcher watcher) {
        String pattern = PropertiesConstants.transform(ctx,$pattern,"");
        String value = PropertiesConstants.transform(ctx,$value,"");
        if (StringUtils.isNotEmpty(pattern) && StringUtils.isNotEmpty(value)){
            CommonMatcher matcher = MatcherFactory.getMatcher(pattern,ctx);
            if (matcher != null && matcher.isMatch(value)){
                ctx.SetValue(id, "true");
                super.onExecute(root,current,ctx,watcher);
            }else{
                ctx.SetValue(id,"false");
            }
        }else{
            ctx.SetValue(id,"false");
        }
    }
}
